(function () {
  const titles = document.querySelectorAll(".menu h2");
  const itemHeight = 30;

  for (let i = 0; i < titles.length; i++) {
    titles[i].addEventListener("click", function () {
      const beforeOpened = document.querySelector(".submenu[status=opened]");
      if (beforeOpened) {
        closeSubMenu(beforeOpened);
      }
      toggleSubmenu(this.nextElementSibling);
    });
  }

  function openSubMenu(subMenu) {
    const to = subMenu.children.length * itemHeight;
    const status = subMenu.getAttribute("status");
    if (status !== "close" && status) {
      return;
    }

    subMenu.setAttribute("status", "playing");
    createAnimation({
      from: 0,
      to,
      totalMS: 300,
      onmove(n) {
        subMenu.style.height = n + "px";
      },
      onend() {
        subMenu.setAttribute("status", "opened");
      },
    });
  }

  function closeSubMenu(subMenu) {
    const from = subMenu.children.length * itemHeight;
    const status = subMenu.getAttribute("status");
    if (status !== "opened") {
      return;
    }

    subMenu.setAttribute("status", "playing");
    createAnimation({
      from,
      to: 0,
      totalMS: 300,
      onmove(n) {
        subMenu.style.height = n + "px";
      },
      onend() {
        subMenu.setAttribute("status", "close");
      },
    });
  }

  function toggleSubmenu(subMenu) {
    const status = subMenu.getAttribute("status");
    if (status == "playing") return;
    status === "close" ? openSubMenu(subMenu) : closeSubMenu(subMenu);
  }
})();
